package com.yx.fsysserver.file.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.*;
import com.yx.fsysserver.common.result.JsonResult;
import com.yx.fsysserver.file.domain.FileInfo;
import com.yx.fsysserver.file.vo.*;
import com.yx.fsysserver.common.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.List;

/**
 * @author cuihao
 * @create 2018-05-31-14:26
 */
@Service
public class AliPlayService {
    private Logger log = LoggerFactory.getLogger(com.yx.fsysserver.file.controller.AliPlayController.class);

    @Autowired
    private FileService fileService;

    @Value("${fSys.accessKeyId}")
    private String accessKeyId;
    @Value("${fSys.accessKeySecret}")
    private String accessKeySecret;

    DefaultProfile profile = null;
    DefaultAcsClient client = null;

    public void initClient(){
        if (profile == null) {
            this.profile = DefaultProfile.getProfile("cn-shanghai", accessKeyId, accessKeySecret);
            this.client = new DefaultAcsClient(profile);
        }
    }

    /**
     * 上传前,从阿里点播视频获取上传权限和上传地址
     *
     * @param fileInfo
     * @return
     */
    public JsonResult getUploadInfo(UploadFileInfo fileInfo) {
        //限制文件大小为1G
        long size = fileInfo.getSize();
        int rate = 1024*1024*1024;
        if(size/rate>1024){
            throw new ServiceException("文件大小必须小于1GB !");
        }
        CreateUploadVideoRequest request = new CreateUploadVideoRequest();
        CreateUploadVideoResponse response = null;
        initClient();
        try {
            /*必选，视频源文件名称（必须带后缀, 支持 ".3gp", ".asf", ".avi", ".dat", ".dv", ".flv", ".f4v", ".gif", ".m2t", ".m3u8", ".m4v", ".mj2", ".mjpeg", ".mkv", ".mov", ".mp4", ".mpe", ".mpg", ".mpeg", ".mts", ".ogg", ".qt", ".rm", ".rmvb", ".swf", ".ts", ".vob", ".wmv", ".webm"".aac", ".ac3", ".acm", ".amr", ".ape", ".caf", ".flac", ".m4a", ".mp3", ".ra", ".wav", ".wma"）*/
            request.setFileName(fileInfo.getFileName());
            //必选，视频标题
            request.setTitle(fileInfo.getTitle());
            //可选，分类ID
//            request.setCateId(0);
            //可选，视频标签，多个用逗号分隔
//            request.setTags("黄河大合唱,js端");
            //可选，视频描述
//            request.setDescription(fileInfo.getDesc());
            //可选，视频源文件字节数
            request.setFileSize(fileInfo.getSize());
            response = client.getAcsResponse(request);
        } catch (ServerException e) {
            System.out.println("CreateUploadVideoRequest Server Exception:");
            e.printStackTrace();
            return new JsonResult(false, "视频正在转码，请稍后再试!");
        } catch (ClientException e) {
            System.out.println("CreateUploadVideoRequest Client Exception:");
            e.printStackTrace();
            return new JsonResult(false, "视频正在转码，请稍后再试!");
        }
        System.out.println("RequestId:" + response.getRequestId());
        System.out.println("videoId:" + response.getVideoId());
        System.out.println("UploadAuth:" + response.getUploadAuth());
        System.out.println("UploadAddress:" + response.getUploadAddress());

        return new JsonResult(true, "success", new AuthAddressVo(response.getVideoId(), response.getUploadAuth(), response.getUploadAddress(), response.getRequestId()));
    }

    /**
     * 保存文件到数据库
     * @param vo
     * @return
     */
    public JsonResult savefile(@RequestBody AddFileInfoVo vo) {
        FileInfo fileInfo = new FileInfo();
        fileInfo.setSrcName(vo.getFileName());
        fileInfo.setName(vo.getFileName());
        fileInfo.setPath("");
        fileInfo.setPathView("");
        fileInfo.setSize(vo.getSize());
        fileInfo.setSuffix(vo.getFileName().split("\\.")[1]);
        fileInfo.setVideoId(vo.getVideoId());
        fileInfo.setCreatetime(new Date());
        fileService.insert(fileInfo);

        return new JsonResult(true, "success");
    }

    /**
     * 获取播放凭证
     *
     * @param videoId 视频id
     * @return
     */
    public JsonResult getPlayAuth(String videoId) {
        initClient();
        System.out.println("accessKeyId = " + accessKeyId);
        System.out.println("accessKeySecret = " + accessKeySecret);
        GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
        request.setVideoId(videoId);
        GetVideoPlayAuthResponse response = null;
        try {
            response = client.getAcsResponse(request);
        } catch (ServerException e) {
            e.printStackTrace();
            System.out.println("GetVideoPlayAuthRequest Server failed");
            return new JsonResult(false, "程序出错!");
        } catch (ClientException e) {
            e.printStackTrace();
            System.out.println("GetVideoPlayAuthRequest Client failed");
            return new JsonResult(false, "程序出错!");
        }
        //播放凭证
        String playAuth = response.getPlayAuth();
        //视频Meta信息
        response.getVideoMeta();

        System.out.println("-----------------------------播放凭证" + playAuth);

        return new JsonResult(true, "", new PlayAuthVo(videoId, playAuth));
    }

    /**
     * 获取播放地址
     *
     * @param videoId 视频id
     * @return
     */
    public JsonResult getPlayAddress(String videoId) {
        initClient();
        GetPlayInfoRequest request = new GetPlayInfoRequest();
        // 准备播放的视频ID
        request.setVideoId(videoId);
        request.setFormats("mp4,m3u8");
        request.setAuthTimeout(1800L);
        GetPlayInfoResponse response = null;
        try {
            response = client.getAcsResponse(request);
        } catch (ServerException e) {
            throw new RuntimeException("GetPlayInfoRequest Server failed");
        } catch (ClientException e) {
            throw new RuntimeException("GetPlayInfoRequest Client failed");
        }
        // 视频基本信息
        GetPlayInfoResponse.VideoBase base = response.getVideoBase();
        // 视频播放信息（流信息列表）
        List<GetPlayInfoResponse.PlayInfo> playInfoList = response.getPlayInfoList();

        PlayFdUrlVo fdVo = new PlayFdUrlVo();
        PlayLdUrlVo ldvo = new PlayLdUrlVo();
        for(GetPlayInfoResponse.PlayInfo playInfo: playInfoList){
            String definition = playInfo.getDefinition();
            if("FD".equalsIgnoreCase(definition)){
                //流畅模式
                String format = playInfo.getFormat();
                String playURL = playInfo.getPlayURL();
                if("m3u8".equals(format)){
                    fdVo.setM3u8Url(playURL);
                }else if("mp4".equals(format)){
                    fdVo.setMp4Url(playURL);
                }
            }else if("LD".equalsIgnoreCase(definition)){
                //标清模式
                String format = playInfo.getFormat();
                String playURL = playInfo.getPlayURL();
                if("m3u8".equals(format)){
                    ldvo.setM3u8Url(playURL);
                }else if("mp4".equals(format)){
                    ldvo.setMp4Url(playURL);
                }
            }
        }

        if (!StringUtils.isEmpty(fdVo.getMp4Url())) {
            fdVo.setMp4Url(fdVo.getM3u8Url());
            return new JsonResult(true, "success", fdVo);
        } else {
            ldvo.setMp4Url(ldvo.getM3u8Url());
            return new JsonResult(true, "success", ldvo);
        }

    }

    /**
     * 获取视频信息
     *
     * @param videoId 视频id
     * @return
     */
    public JsonResult getVideoInfo(String videoId) {
        initClient();
        GetVideoInfoRequest request = new GetVideoInfoRequest();
        // 准备播放的视频ID
        request.setVideoId(videoId);
        request.setAcceptFormat(FormatType.JSON);
        GetVideoInfoResponse response = null;
        try {
            response = client.getAcsResponse(request);
        } catch (ServerException e) {
            throw new RuntimeException("GetVideoInfoResponse Server failed");
        } catch (ClientException e) {
            throw new RuntimeException("GetVideoInfoResponse Client failed");
        }
        // 视频基本信息
        GetVideoInfoResponse.Video video = response.getVideo();
        String status = video.getStatus();
        //Transcoding转码中;TranscodeFail转码失败;Blocked在审核时屏蔽视频;Normal正常
        System.out.println("" + status);
        if("Normal".equals(status)){

        }

        return new JsonResult(true, "success",status);
    }

    /**
     * 获取源文件地址
     *
     * @param videoId 视频id
     * @return
     */
    public String GetMezzanineInfo(String videoId) {
        initClient();
        GetMezzanineInfoRequest request = new GetMezzanineInfoRequest();
        // 准备播放的视频ID
        request.setVideoId(videoId);
        request.setAcceptFormat(FormatType.JSON);
        GetMezzanineInfoResponse response = null;
        try {
            response = client.getAcsResponse(request);
        } catch (ServerException e) {
            throw new RuntimeException("GetVideoInfoResponse Server failed");
        } catch (ClientException e) {
            throw new RuntimeException("GetVideoInfoResponse Client failed");
        }
        // 视频基本信息
        GetMezzanineInfoResponse.Mezzanine mezzanine = response.getMezzanine();
        String fileName = mezzanine.getFileName();
        String fileURL = mezzanine.getFileURL();
        System.out.println("--------fileName=="+fileName);
        System.out.println("--------fileURL=="+fileURL);

        return fileURL;
    }

}
